<?php

namespace App\Console\Commands;

use App\Models\Common\Common;
use App\Models\Common\Wechat;
use App\Models\Tools\Data;
use App\Models\Tools\Period;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ExploreMessage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:explore_message';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检查当前待接单数量，如果超过阈值,推送一次全员通知';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        try {
            // 查询当前剩余未接单的单量
            $orders = DB::table('explore_order')
                ->where('status',Data::DATA_DB_EXPLORE_ORDER_STATUS_PENDING)
                ->value(DB::raw('SUM(remaining_num)'));
            // 如果未超过阈值提前结束
            if ($orders < Period::getSetting('OVERFLOW_TIMES')) return;

            // 不合格人的:今日接单超过3单不推送
            $over_users = DB::table('explore_work')
                ->where('created_at','>',date('Y-m-d 00:00:00'))
                ->groupBy('receiver_we_id')
                ->select('receiver_we_id')
                ->selectRaw('count(*) as count')
                ->get()
                ->where('count','>',2)
                ->pluck('receiver_we_id')
                ->toArray();

            // 查询所有接收人openid
            $openid_arr = DB::table('lottery_users')
                ->where('notice','=',1)
                ->whereNotIn('we_id',$over_users)
                ->inRandomOrder()
                ->pluck('openid')
                ->toArray();
//            $data = [
//                'first'=>'如退订消息，请点击公众号菜单：达人-去探店，在页面顶部关闭此通知',
//                'keyword1'=>'达人探店',
//                'keyword2'=>date('Y-m-d H:i:s'),
//                'remark'=>'来飞网有新的探店邀请，点击“查看详情”，快来查看吧',
//            ];
            $app = Wechat::officialAccount();
            foreach ($openid_arr as $openid) {
                $app->customer_service->message('⭕亲～任务大厅有新的探店任务，快去抢单噢
👉<a href="' . env('APP_LAIFEI_URL') . '/talent' . '">点此参与</a>')->to($openid)->send();
            }
        }catch (\Exception $e){
            Log::emergency(ExploreMessage::class,['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
        }
        return;
    }
}
